package com.Jhu1.controller;

import com.Jhu1.client.OrderClient;
import com.Jhu1.entity.User;
import com.Jhu1.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 用户�? 前端控制器
 * </p>
 *
 * @author 钟俊辉
 * @since 2025-01-14
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private OrderClient orderClient;

    @GetMapping("/list")
    public R list() {
        return R.ok().data("userList", userService.list());
    }

    @PostMapping("/register")
    public Result<?> register(
            @RequestParam("userName") @Pattern(regexp = "^\\S{5,16}$") String userName,
            @RequestParam("password") @Pattern(regexp = "^\\S{5,16}$") String password,
            @RequestParam("role") String role,
            @RequestParam("storeName") String storeName
    ) {
        User u = userService.findByuserName(userName);
        if (u == null) {
            Store store = orderClient.getMerchantByName(storeName);
            if (store.getMerchantId() == 0) {
                //注册
                userService.register(userName, password, role);
                User u1 = userService.findByuserName(userName);
                orderClient.register(store.getId(), u1.getId());
                return Result.success();
            } else {
                return Result.error("店铺已被注册");
            }


        } else {
            return Result.error("用户名已存在");
        }
    }

    @PostMapping("/login")
    public Result<?> login(
            @RequestParam("userName") @Pattern(regexp = "^\\S{5,16}$") String userName,
            @RequestParam("password") @Pattern(regexp = "^\\S{5,16}$") String password,
            @RequestParam("role") String role
    ) {
        User u = userService.findByuserName(userName);
        if (u == null) {
            return Result.error("用户名不存在");
        }
        if (!u.getRole().equals(role)) {
            return Result.error("权限错误");
        }
        if (SecurityUtil.verifyPassword(password, u.getUserPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", u.getId());
            claims.put("userName", u.getUserName());
            String token = JwtUtil.generateToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String userName = (String) map.get("userName");
        User u = userService.findByuserName(userName);
        return Result.success(u);
    }

    @PutMapping("/update")
    public Result<?> updateInfo(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result<?> updateAvatar(@RequestParam("avatar") String url) {
        userService.updateAvatar(url);
        return Result.success();
    }

    @PostMapping("/avatar")
    public Result<String> upload(MultipartFile file) throws Exception {
        //文件内容存储在本地
        String originalFilename = file.getOriginalFilename();

        //保证文件名唯一
        String fileName = UUID.randomUUID().toString()
                + originalFilename.substring(originalFilename.lastIndexOf("."));
        //本地
        String url = AliyunOssUtil.uploadFile(fileName, file.getInputStream());

        return Result.success(url);
    }

    @PatchMapping("/updatePwd")
    public Result<?> updatePwd(@RequestBody Map<String, String> params) {
        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要参数");
        }
        Map<String, Object> map = ThreadLocalUtil.get();
        String userName = (String) map.get("userName");
        User loginUser = userService.findByuserName(userName);
        if (!SecurityUtil.verifyPassword(oldPwd, loginUser.getUserPassword())) {
            return Result.error("原密码错误");
        }
        if (!rePwd.equals(newPwd)) {
            return Result.error("两次密码不一致");
        }

        userService.updatePwd(SecurityUtil.getSecurityPassword(newPwd));
        return Result.success();
    }

    @GetMapping("/merchant/all")
    public Result<List<Store>> getMerchantAll() {
        List<Store> merchants = orderClient.getMerchantAll().getData();
        return Result.success(merchants);
    }

    @PostMapping("/merchant/add")
    public Result<?> addMerchant(@RequestBody Store merchant) {
        orderClient.addMerchant(merchant);
        return Result.success();
    }

    @GetMapping("/merchant/myStore")
    public Result<Store> myStore() {
        return Result.success(orderClient.myStore().getData());
    }

    @PatchMapping("/merchant/update")
    public Result<?> update(@RequestBody Store store) {
        orderClient.update(store);
        return Result.success();
    }

    @DeleteMapping("/merchant/delete")
    public Result<?> deleteMerchant(@RequestParam("id") Integer id) {
        orderClient.deleteMerchant(id);
        return Result.success();
    }
}
